﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Caliburn.Micro;
using GoToCoord.Models;
using System.Collections.Generic;
using System.Device.Location;
using GoToCoord.Utils;
using GoToCoord.Services;

namespace GoToCoord.ViewModels
{
    [SurviveTombstone]
    public class MainViewModel : Screen
    {
        private readonly INavigationService navigationService;
        private readonly ParameterService parameterService;
        private readonly IEventAggregator eventAggregator;

        [SurviveTombstone]
        public double latHours { get; set; }
        [SurviveTombstone]
        public double longHours { get; set; }

        public MainViewModel(IEventAggregator eventAggregator, INavigationService navigationService, ParameterService parameterService)
        {
            this.eventAggregator = eventAggregator;
            this.navigationService = navigationService;
            this.parameterService = parameterService;
        }

        public void ChangeCoordinates()
        {
            navigationService.Navigate(Uris.ChangeCoordinatesView);
        }

        public void TurnWatcherOnOff()
        {
            eventAggregator.Publish<TurnWatcherOnOffEvent>(new TurnWatcherOnOffEvent());
        }

        protected override void OnActivate()
        {
            base.OnActivate();

            if (parameterService.HasEntries)
            {
                GeoCoordinate g = (GeoCoordinate)parameterService.Pop();
                latHours = g.Latitude;
                longHours = g.Longitude;
            }

            raiseEventFromCoordinates();
        }

        // Wird nach dem Resurrect aufgerufen - bei OnActive() ist das Resuccrect nach dem Tombstoning noch nicht erfolgt.
        protected override void OnViewLoaded(object view)
        {
            base.OnViewLoaded(view);
            raiseEventFromCoordinates();
        }

        private void raiseEventFromCoordinates()
        {
            if (latHours != 0 && longHours != 0)
            {
                GeoCoordinate g = new GeoCoordinate(latHours, longHours);
                eventAggregator.Publish<AddLocationEvent>(new AddLocationEvent(g.Longitude, g.Latitude));
            }
        }
    }
}
